import os
from typing import Optional
from .log_utils import get_logger
import aiofiles

logger = get_logger(__name__)


# 使用三方库 aiofiles
class AsyncFileUtils:
    """
    异步文件操作工具类，支持读写追加等操作
    """

    def __init__(self, path: str, encoding: str = 'utf-8'):
        self.path = path
        self.encoding = encoding

    async def exists(self) -> bool:
        return os.path.exists(self.path)

    async def read_text(self) -> Optional[str]:
        try:
            async with aiofiles.open(self.path, mode='r', encoding=self.encoding) as f:
                return await f.read()
        except Exception as e:
            logger.error(f"[read_text] Error: {e}")
            return None

    async def write_text(self, content: str) -> bool:
        try:
            async with aiofiles.open(self.path, mode='w', encoding=self.encoding) as f:
                await f.write(content)
            return True
        except Exception as e:
            logger.error(f"[write_text] Error: {e}")
            return False

    async def append_text(self, content: str) -> bool:
        try:
            async with aiofiles.open(self.path, mode='a', encoding=self.encoding) as f:
                await f.write(content)
            return True
        except Exception as e:
            logger.error(f"[append_text] Error: {e}")
            return False

    async def read_lines(self) -> list[str]:
        lines = []
        try:
            async with aiofiles.open(self.path, mode='r', encoding=self.encoding) as f:
                async for line in f:
                    lines.append(line.rstrip('\n'))
        except Exception as e:
            logger.error(f"[read_lines] Error: {e}")
        return lines


#  使用to_thread
import asyncio
import os
from typing import Optional


class AsyncFileUtils1:
    def __init__(self, filepath: str):
        self.filepath = filepath

    async def read_text(self, encoding: str = "utf-8") -> str:
        return await asyncio.to_thread(self._sync_read_text, encoding)

    def _sync_read_text(self, encoding):
        with open(self.filepath, "r", encoding=encoding) as f:
            return f.read()

    async def write_text(self, content: str, encoding: str = "utf-8"):
        await asyncio.to_thread(self._sync_write_text, content, encoding)

    def _sync_write_text(self, content, encoding):
        with open(self.filepath, "w", encoding=encoding) as f:
            f.write(content)

    async def append_text(self, content: str, encoding: str = "utf-8"):
        await asyncio.to_thread(self._sync_append_text, content, encoding)

    def _sync_append_text(self, content, encoding):
        with open(self.filepath, "a", encoding=encoding) as f:
            f.write(content)

    async def read_lines(self, encoding: str = "utf-8") -> list[str]:
        return await asyncio.to_thread(self._sync_read_lines, encoding)

    def _sync_read_lines(self, encoding):
        with open(self.filepath, "r", encoding=encoding) as f:
            return f.readlines()

    async def exists(self) -> bool:
        return await asyncio.to_thread(os.path.exists, self.filepath)
